package com.cool.controller;

import com.cool.dao.FavorMapper;
import com.cool.dao.UserMapper;
import com.cool.entity.Favor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;

@RestController
public class FavorController {
    @Autowired
    private FavorMapper favorMapper;

    @Autowired
    private UserMapper userMapper;

    @RequestMapping(value = "/api/favors/{uid}",method = RequestMethod.GET,produces = "application/json;charset=utf-8")
    public ResponseEntity<ArrayList<Favor>> getByUid(@PathVariable int uid)
    {
        ArrayList<Favor> favors=new ArrayList<Favor>();
        favors=favorMapper.selectByUserid(uid);
        if(favors.size()==0){
            return new ResponseEntity<ArrayList<Favor>>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<ArrayList<Favor>>(favors,HttpStatus.OK);
    }

    @RequestMapping(value = "/api/favor/{id}",method = RequestMethod.GET,produces = "application/json;charset=utf-8")
    public ResponseEntity<Favor> getFavor(@PathVariable int id)
    {
        Favor favor=favorMapper.selectByPrimaryKey(id);
        if(favor==null){
            return new ResponseEntity<Favor>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<Favor>(favor,HttpStatus.OK);
    }

    @RequestMapping(value = "/api/favor",method = RequestMethod.POST,consumes = "application/json;charset=utf-8",produces = "application/json;charset=utf-8")
    public ResponseEntity<Favor> add(@RequestBody Favor favor){
        if(userMapper.selectByPrimaryKey(favor.getUserid())==null||favorMapper.selectByName(favor.getName()).size()!=0){
            return new ResponseEntity<Favor>(HttpStatus.NO_CONTENT);
        }
        favorMapper.insert(favor);
        return new ResponseEntity<Favor>(favor,HttpStatus.CREATED);
    }

    @RequestMapping(value = "/api/favor/{id}",method = RequestMethod.DELETE,produces = "application/json;charset=utf-8")
    public ResponseEntity<Favor> del(@PathVariable int id){
        if(favorMapper.selectByPrimaryKey(id)==null){
            return new ResponseEntity<Favor>(HttpStatus.NO_CONTENT);
        }
        favorMapper.deleteByPrimaryKey(id);
        return new ResponseEntity<Favor>(HttpStatus.OK);
    }

    @RequestMapping(value = "/api/favor",method = RequestMethod.PUT,consumes = "application/json;charset=utf-8",produces = "application/json;charset=utf-8")
    public ResponseEntity<Favor> update(@RequestBody Favor favor){
        if(favorMapper.selectByPrimaryKey(favor.getId())==null){
            return new ResponseEntity<Favor>(HttpStatus.NO_CONTENT);
        }
        favorMapper.updateByPrimaryKeySelective(favor);
        Favor result=favorMapper.selectByPrimaryKey(favor.getId());
        return new ResponseEntity<Favor>(result,HttpStatus.OK);
    }

}
